package top.lingkang.finalgateway.admin;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Init;
import org.noear.solon.annotation.Inject;
import org.noear.solon.scheduling.annotation.EnableScheduling;
import top.lingkang.finalgateway.FinalGateway;
import top.lingkang.finalgateway.admin.constants.LogType;
import top.lingkang.finalgateway.admin.entity.ConfigEntity;
import top.lingkang.finalgateway.admin.mapper.ActionLogMapper;
import top.lingkang.finalgateway.admin.mapper.ConfigMapper;
import top.lingkang.finalgateway.admin.mapper.SslMapper;
import top.lingkang.finalgateway.config.RouterConfig;
import top.lingkang.finalgateway.utils.CommonUtils;
import top.lingkang.finalgateway.utils.ConfigUtils;

/**
 * @author lingkang
 * Created by 2024/4/27
 */
@Slf4j
@EnableScheduling
@Component
public class WebApp {

    public static void runWeb(String[] args) {
        Solon.start(WebApp.class, args, solonApp -> {
            solonApp.enableTransaction(false);
            solonApp.enableWebSocket(true);
            //启用 Sokcet.D 服务
            solonApp.enableSocketD(true);
        });
    }

    @Inject
    private ConfigMapper configMapper;
    @Inject
    private SslMapper sslMapper;
    @Inject
    private ActionLogMapper actionLogMapper;

    @Init
    public void init() {
        ConfigEntity config = configMapper.selectById("xml");
        if (config == null) {
            log.info("初始化xml配置");
            String xml = IoUtil.readUtf8(getClass().getClassLoader().getResourceAsStream("config.xml"));
            config = new ConfigEntity();
            config.setId("xml");
            config.setData(xml);
            config.setDescription("xml配置");
            configMapper.insert(config);
        }

        // 创建配置
        try {
            FinalGateway.config = ConfigUtils.loadXML(config.getData());
        } catch (Exception e) {
            log.error("初始化配置失败", e);
            System.exit(0);
            return;
        }

        // 检查配置
        for (RouterConfig c : FinalGateway.config.getRouterConfigs()) {
            if (StrUtil.isNotBlank(c.getSsl())) {
                if ("0".equals(c.getSsl())) {
                    continue;
                }
                if (!sslMapper.existsById(c.getSsl())) {
                    System.out.println("启动失败，ssl名称不存在：" + c.getSsl());
                    log.error("启动失败，ssl名称不存在：" + c.getSsl());
                    System.exit(0);
                    return;
                }
            }
        }
        actionLogMapper.addLog(LogType.app_start, null);
        // 启动网关
        FinalGateway.initService();

        log.info("应用启动完毕, 耗时: {}ms", (System.currentTimeMillis() - FinalGateway.startTime));
    }
}
